// var superagent = require('superagent');
// var cheerio = require('cheerio');

function getMovieShowing(webUrl = "https://movie.douban.com/") {
  return new Promise((resolve, reject) => {
    superagent.get(webUrl).end(function (err, sres) {
      let result = {data: []}
      if (err) result.error = err
      let $ = cheerio.load(sres.text);
      $('div.screening-bd > ul').children().each(function (i, elem) {
        let title = $(this).attr('data-title')
        let duration = $(this).attr('data-duration')
        let release = $(this).attr('data-release')
        let score = $(this).attr('data-rate')
        let region = $(this).attr('data-region')
        let director = $(this).attr('data-director')
        let actor = $(this).attr('data-actors')
        let subject = $(this).attr('data-ticket')
        if (subject) subject = subject.includes("movie_id=") ? subject.split("movie_id=")[1] : subject
        let image = $(this).find('ul > li > a > img').attr('src')
        let item = {
          subject: subject,
          image: image,
          title: title,
          duration: duration,
          score: score,
          actor: actor,
          release: release,
          region: region,
          director: director
        }
        result.data.push(item)
      })
      console.log("result", result)
      resolve(result)
    })
  })
}

function convertInfo(strInfo) {
  if (!strInfo) return ""
  let obj = {}
  let keyList = strInfo.match(/[\u4e00-\u9fa5/a-zA-Z]+[:]/g)//得到:及前面的key值
  let list = strInfo.split('\n').filter(item => item.indexOf(":") != -1)
  list.map(item => {
    let key = keyList.find(key => item.indexOf(key) != -1)
    let value = item.replace(new RegExp(`[${key} ]`, "g"), '')
    let mItem = {[key]: value}
    obj[key] = value
    return mItem
  })
  return obj
}

function replaceSpan(res) {
  Object.keys(res).forEach(key => {
    if (typeof res[key] == 'string') res[key] = res[key].replace(new RegExp(/[ ]/g), "")
  })
}

function getMovieDetail(subject = '1293475') {
  let webUrl = `https://movie.douban.com/subject/${subject}`
  return new Promise((resolve, reject) => {
    superagent.get(webUrl).end(function (err, sres) {
      let result = {data: {}}
      if (err) result.error = err
      let $ = cheerio.load(sres.text);
      let mainpic = $('div#mainpic > a.nbgnbg > img').attr('src')//图片
      let title = $('div#content > h1').text()
      let info = convertInfo($('div#info').text())
      let rating_num = $('div.rating_self.clearfix > strong.ll.rating_num').text()
      let rating_people = $('div.rating_sum > a.rating_people').text()
      let intra = $('div#link-report-intra').text()
      let celebrities = []
      let celebritiesDiv = $('div#celebrities > ul.celebrities-list.from-subject.__oneline')
      celebritiesDiv.children().each(function (i, e) {
        // console.log("=======", $(e).text())
        let avatar = $("a > div.avatar", $(e)).attr('style')
        avatar = avatar.substring(avatar.indexOf('(') + 1, avatar.indexOf(')'))
        let name = $("div.info > span.name > a.name", $(e)).text()
        let role = $("div.info > span.role", $(e)).text()
        celebrities.push({name, avatar, role})
      })
      let relatedPics = []
      let relatedPicDiv = $("div#related-pic > ul.related-pic-bd")
      relatedPicDiv.children().each(function (i, e) {
        let image = $('li > a > img', $(e)).attr('src')
        if (image) relatedPics.push(image)
      })
      // console.log("celebrities", celebrities)
      result.data = {
        mainpic: mainpic,
        title: title,
        info: info,
        rating_num: rating_num,
        rating_people:rating_people,
        intra:intra,
        celebrities:celebrities,
        relatedPics:relatedPics
      }
      replaceSpan(result.data)
      resolve(result)
    })
  })
}

function getMovieComment(subject = '1293475') {
  let webUrl = `https://movie.douban.com/subject/${subject}/comments?status=P`
  return new Promise((resolve, reject) => {
    superagent.get(webUrl).end(function (err, sres) {
      console.log("getMovieComment===", sres)
      let result = {data: {}}
      if (err) result.error = err
      let $ = cheerio.load(sres.text);
      let comments = $('div#comments')//图片
      let list = []
      comments.children().each(function (i, e) {
        let image = $('div.avatar > a > img', $(e)).attr('src')
        let valued = $('div.comment > h3 > span.comment-vote', $(e)).text()
        let info = $('div.comment > h3 > span.comment-info', $(e))
        let name = $('a', info).text()
        let score = $('span.rating', info).attr('class')
        let time = $('span.comment-time', info).text()
        let content = $('div.comment > p.comment-content', $(e)).text()
        // if (score) score = score.toString().replace(new RegExp(/[a-zA-Z]/g, ''))
        let item = {image, valued, name, score, time, content,}
        if (name && content) list.push(item)
      })
      result.data = list
      resolve(result)
    })
  })
}

module.exports = {
  getMovieShowing,
  getMovieDetail,
  getMovieComment
}
